package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRegistService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.common.utils.LogUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRegistService userInfoRegistService;

    @Override
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    /*
     * 点击立即注册判断手机号是否已存在
     * */
    @Override
    public Boolean checkPhone(String phone) {
        int count = userInfoMapper.selectByPhone(phone);
        return count > 0;
    }

    /*
     *
     * 发送验证码
     * */
    @Override
    public void sendVerifyCode(String phone)throws LogicException {

        //2分钟不能重复发短信
        String timeOutKey ="verify_code_vali:"+phone;
        String timeOutValue = userInfoRegistService.getCode(timeOutKey);
        if (timeOutValue!=null){
            throw new LogicException("您的操作过于频繁");
        }

        //生成验证码
        String code = UUID.randomUUID().toString().substring(0, 4).replaceAll("-", " ");

        //把验证码存到redis中
        String key = "verifyCode:" + phone;
        userInfoRegistService.saveVerifyCode(key, code, phone);

        //模拟发送短信
        System.out.println("您的验证码是：" + code + "请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内使用");

    }

    /*
     *
     * 注册
     * */
    @Override
    public void userRegist(String nickname, String password, String rpassword, String verifyCode, String phone)throws LogicException {

        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "验证密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        AssertUtil.hasLength(phone, "手机号不能为空");

        AssertUtil.isEquals(password,rpassword,"两次密码必须一致");
        //判断手机号是否存在
        if (this.checkPhone(phone)){
            throw new LogicException("手机号已被注册");
        }

        //手机号码格式验证
        isPhone(phone);

        //从redis中匹配验证码是否正确
        //拼接key
        String key = "verifyCode:" + phone;
        //获取redis中的验证码
        String code = userInfoRegistService.getCode(key);
        if (code==null ||!verifyCode.equals(code)){
            throw  new LogicException("验证码错误或已失效");
        }

        //注册
        UserInfo user = new UserInfo();
        user.setNickname(nickname);
        user.setLevel(1);
        user.setPhone(phone);
        user.setPassword(password);
        user.setState(0);
        user.setHeadImgUrl("/images/default.jpg");

        userInfoMapper.insert(user);

    }



    //登录
    @Override
    public String userLogin(String username, String password)throws LogicException {

        //验证
        UserInfo user = userInfoMapper.getUserByUserNameAndPassWord(username,password);
        if (user == null){
            throw new LogicException("账号不存在或密码错误");
        }

        //作为存入redis的key
        String token = UUID.randomUUID().toString().replace("-", "");

        //把用户信息存入redis
        userInfoRegistService.addToken(token,user);

        return token;
    }

    @Override
    public List<UserInfo> list() {

        return userInfoMapper.selectAll();
    }


    //手机号验证
    public static void isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            throw new LogicException("手机号应为11位数");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
//            LogUtil.e(isMatch);
            if (!isMatch) {
                throw new LogicException("请填入正确的手机号");
            }
        }
    }


}
